package com.ywl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ywl.entity.Product;
import com.ywl.mapper.ProductMapper;
import com.ywl.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywl
 * @since 2022-08-26
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    /**
     * 获得热销产品数据
     * @param city
     * @return
     */
    @Override
    public List<Product> getHotProduct(String city) {
        /*select * from product where type = 1 ORDER BY create_time limit 0,4;*/
        LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Product::getCreateTime);
        qw.eq(city != null,Product::getCity, city);
        qw.eq(Product::getType,1);
        qw.last("limit 0,4");
        List<Product> list = super.list(qw);
        return list;
    }

    /**
     * 获得推荐产品
     * @param city
     * @return
     */
    @Override
    public List<Product> getRecProduct(String city) {
        LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Product::getCreateTime);
        qw.eq(city != null,Product::getCity, city);
        qw.eq(Product::getType,2);
        qw.last("limit 0,4");
        List<Product> list = super.list(qw);

        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        //如果该城市中的没有商品为推荐商品，则从其他城市拿
        if(list.size() == 0){
            queryWrapper.orderByDesc(Product::getCreateTime);
            queryWrapper.eq(Product::getType,2);
            queryWrapper.last("limit 0,4");
            list = super.list(queryWrapper);
        }else if(list.size() % 4 != 0) {
            //如果城市中的商品不足4个，则从其他城市中补齐
            int size = list.size();
            int neeAddNum = 4 - size % 4;
            queryWrapper.eq(Product::getType,2);
            queryWrapper.notIn(Product::getCity,city);
            queryWrapper.last("list 0,".concat(String.valueOf(neeAddNum)));
            List<Product> addList = super.list(queryWrapper);
            list.addAll(addList);
        }
        //如果该城市中没有商品为
        return list;
    }
}
